package bagu.test.duoxiancheng;

/**
 * @Author: wzp
 * @CreateTime: 2024-09-14  14:01
 * @Description: sleep和wait的比较
 * @Version: 1.0
 */
public class SleepAndWait {
//    设定一把锁
    private static final Object lock = new Object();
    public static void main(String[] args) throws InterruptedException {
//    测试sleep
        new SleepAndWait().sleepTest();
        new SleepAndWait().waitTest();
    }

    public  void sleepTest() throws InterruptedException {
        Thread thread =new Thread(
                () -> {
                    synchronized (lock){
                        try {
                            System.out.println("sleep");
                            Thread.sleep(5000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
//                    主线程里面获取到锁，但是sleep被阻塞了，所以不会输出

                }
        );
        thread.start();
        Thread.sleep(100);
        synchronized (lock){
            System.out.println("这里是主线程");
        }


    }
    public  void waitTest() throws InterruptedException {
        Thread thread =new Thread(
                () -> {
                    synchronized (lock){
                        try {
                            System.out.println("wait");
                            lock.wait(5000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
        );
        thread.start();
        Thread.sleep(100);
        synchronized (lock){
            System.out.println("这里是主线程");
        }
    }
}
